package com.mzba.easy.weibo.ui;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.CommentEntry;
import com.mzba.easy.weibo.db.EmotionField;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;
import com.mzba.easy.weibo.widget.CustomTextView;
import com.mzba.easy.weibo.widget.RemoteImageView;
/**
 * 
 * @author 06peng
 *
 */
public class CommentListAdapter extends BaseAdapter implements Callback, BasicUIEvent  {
	
	private Context context;
	private List<CommentEntry> entries;
	private ListView listView;
	
	private EditText currentEdit;
	private Handler handler;
	private WeiboManager weiboManager;
	private boolean isRetweet = false;
	private PopupWindow pop;
	private LinearLayout preLayout;
	private View popViewToShow;
	
	public static final int DESTROYDIALOG = 0x00000101;
	private static final int reply_comment = 0x00000102;
	private static final int reply_comment_error = 0x00000103;
	
	private String statusId;
	
	public CommentListAdapter(Context context, List<CommentEntry> entries, ListView listView, String statusId) {
		this.context = context;
		this.entries = entries;
		this.listView = listView;
		this.statusId = statusId;
		handler = new Handler(this);
		weiboManager = new WeiboManager(context);
		View view = LayoutInflater.from(context).inflate(R.layout.emotion_gridview, null);
		GridView gridView = (GridView) view.findViewById(R.id.emotion_gridview);
		GridViewAdapter gridAdapter = new GridViewAdapter(context);
		gridView.setAdapter(gridAdapter);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		pop.update();
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				try {
					pop.dismiss();
					EmotionField filed = AppContext.getInstance().getEmotionFields().get(arg2);
					if (currentEdit != null) {
						currentEdit.append(filed.getPhrase());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		popViewToShow = LayoutInflater.from(context).inflate(R.layout.comment_body_item, null);
	}

	@Override
	public int getCount() {
		return entries.size();
	}

	@Override
	public Object getItem(int position) {
		return entries.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = LayoutInflater.from(context).inflate(R.layout.comment_body_item, null);
		RemoteImageView avatarView = (RemoteImageView) convertView.findViewById(R.id.iv_author_photo);
		TextView replyView = (TextView) convertView.findViewById(R.id.comment_body_reply);
		CustomTextView textView = (CustomTextView) convertView.findViewById(R.id.comment_body_text);
		LinearLayout bodyLayout = (LinearLayout) convertView.findViewById(R.id.comments_timeline_bodylayout);
		
		EditText editView = (EditText) convertView.findViewById(R.id.timeline_comment_edit);
		ImageButton emotionView = (ImageButton) convertView.findViewById(R.id.timeline_comment_emotion);
		ImageView retweetView = (ImageView) convertView.findViewById(R.id.timeline_comment_retweet_select);
		LinearLayout retweetSelectLayout = (LinearLayout) convertView.findViewById(R.id.timeline_comment_retweet_select_layout);
		Button commentView = (Button) convertView.findViewById(R.id.timeline_comment_comment);
		
		try {
			final CommentEntry entry = entries.get(position);
			avatarView.setDefaultImage(R.drawable.avatar_default_big);
			avatarView.setImageUrl(entry.getUser().getProfile_image_url(), AppContext.UNAVAILABLE, position, listView);
			String username = entry.getUser().getScreen_name() + ":" + "&nbsp;";
			textView.setText(entry.getText(), username, AppContext.getInstance().getFaceMap());
			
			avatarView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, UserinfoActivity.class);
					intent.putExtra("userid", entry.getUser().getId());
					context.startActivity(intent);
				}
			});
			if (entry.isSelected()) {
				bodyLayout.setVisibility(View.VISIBLE);
			}
			if (preLayout != null) {
				preLayout.setVisibility(View.GONE);
			}
			replyView.setTag(bodyLayout);
			bodyLayout.setTag(editView);
			replyView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(context, NewsActivity.class);
					intent.putExtra("id", statusId);
					intent.putExtra("reid", entry.getId());
					intent.putExtra(AppContext.NEWTYPE, 3);
					context.startActivity(intent);
//					LinearLayout bodyLayout = (LinearLayout) v.getTag();
//					EditText editView = (EditText) bodyLayout.getTag();
//					
//					if (bodyLayout.getVisibility() == View.VISIBLE) {
//						bodyLayout.setVisibility(View.GONE);
//						entry.setSelected(false);
//						currentEdit = null;
//					} else {
//						bodyLayout.setVisibility(View.VISIBLE);
//						entry.setSelected(true);
//						editView.setText("回复@" + entry.getUser().getScreen_name() + ":");
//						editView.setFocusable(true);
//						editView.setFocusableInTouchMode(true);
//						editView.requestFocus();
//						currentEdit = editView;
//					}
//					preLayout = bodyLayout;
//					editView.setText("回复@" + entry.getUser().getScreen_name() + ":");
//					editView.setFocusable(true);
//					editView.setFocusableInTouchMode(true);
				}
			});
			emotionView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (!pop.isShowing()) {
						pop.showAtLocation(popViewToShow, Gravity.BOTTOM, 0, 0);
					} else {
						pop.dismiss();
					}
				}
			});
			
			retweetSelectLayout.setTag(retweetView);
			retweetSelectLayout.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					ImageView retweetView = (ImageView) v.getTag();
					if (isRetweet) {
						isRetweet = false;
						retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_unselect);
					} else {
						isRetweet = true;
						retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_select);
					}
				}
			});
			
			commentView.setTag(editView);
			commentView.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					EditText editView = (EditText) v.getTag();
					String content = editView.getText().toString().trim();
					Object[] objs = new Object[4];
					objs[0] = content;
					objs[1] = entry.getStatus().getId();
					objs[2] = entry.getId();
					objs[3] = isRetweet == true ? 1 : 0;
					UICore.eventTask(CommentListAdapter.this, (BasicActivity) context, reply_comment, "", objs); 
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case reply_comment:
			Object[] objs2 = (Object[]) obj;
			CommentEntry commentEntry2 = weiboManager.replayCommemnt(objs2[0].toString(), objs2[1].toString(), objs2[2].toString(),
					Integer.parseInt(objs2[3].toString()));
			if (commentEntry2 != null) {
				handler.sendEmptyMessage(reply_comment);
			} else {
				handler.sendEmptyMessage(reply_comment_error);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case reply_comment:
			((BasicActivity) context).onToast("评论成功");
			break;
		case reply_comment_error:
			((BasicActivity) context).onToast("评论失败");
			break;
		default:
			break;
		}
		return false;
	}

}
